package com.atguigu.juc.chap10;

import java.util.concurrent.*;
import java.util.function.Supplier;

public class CompletableFutureDemo02_01 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        
        // 1、创建线程池对象，让任务在我们自己创建的线程池中运行
        ExecutorService threadPool = Executors.newFixedThreadPool(5);

        // 2、创建 Supplier 类型对象，封装任务内容
        Supplier<String> supplier = ()->{
            
            System.out.println(Thread.currentThread().getName() + " is working");
            
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            
            return "task result";
        };

        // 3、将异步任务提交到自己指定的线程池
        CompletableFuture<String> future = CompletableFuture.supplyAsync(supplier, threadPool);

        // 4、调用 get() 方法获取任务结果
        System.out.println(Thread.currentThread().getName() + " 线程即将调用get()方法");
        String taskResult = future.get();
        System.out.println("taskResult = " + taskResult);
        System.out.println("finish");
        
        // 5、关闭线程池
        threadPool.shutdown();
    }
}